package com.example.leetcode.DFS;

/**
 * 给你一个 m x n 的矩阵 board ，由若干字符 'X' 和 'O' ，找到所有被 'X' 围绕的区域，并将这些区域里所有的 'O' 用 'X' 填充。
 *  
 *
 * 示例 1：
 *
 *
 * 输入：board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
 * 输出：[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
 * 解释：被围绕的区间不会存在于边界上，换句话说，任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上，
 * 或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻，则称它们是“相连”的。
 *
 *
 * @Description TODO
 * @date 2021/6/2 16:00
 * @Author liuzhihui
 * @Version 1.0
 */
public class Solution_8_130 {

    public static void main(String[] args) {
//        char[][] board = new char[][]{{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}};
        char[][] board = new char[][]{{'O','O','O'},{'O','O','O'},{'O','O','O'}};
        solve(board);
    }
    // 思路：
    // 先从边界开始找，找那些与边界的O相连的O,并把他们改为A
    // 然后在遍历二维数组，把A改为O，把O改为X
    public static void solve(char[][] board) {
        // 获取竖边长度
        int m = board.length;
        // 获取横边长度
        int n = board[0].length;

        // 遍历竖边
        for (int i = 0; i < m; i++) {
            // 左边界
            dfs(board,i,0);
            // 右边界
            dfs(board,i,n - 1);
        }
        // 遍历横边
        for (int i = 0; i < n; i++) {
            // 上边界
            dfs(board,0,i);
            // 下边界
            dfs(board,m - 1,i);
        }
        // 遍历二维数组
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O'){
                    board[i][j] = 'X';
                }else if (board[i][j] == 'A') {
                    board[i][j] = 'O';
                }
            }
        }
    }
    private static void dfs(char[][] board, int i, int j ) {
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != 'O'){
            return;
        }
        board[i][j] = 'A';

        dfs(board,i + 1, j);
        dfs(board,i - 1, j);
        dfs(board,i, j + 1);
        dfs(board,i, j - 1);
    }

}
